from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from .forms import UserRegisterForm, UserLoginForm, ArticleForm
from django.conf import settings
from django.utils import timezone
from . import models
from .models import User, Article, Charge, Bill, Comment, Zan
from django.core.paginator import PageNotAnInteger,Paginator, EmptyPage
import base64
import qrcode
import re, time, math
import random
import os
from io import BytesIO
from django.db.models import F
from django.views.decorators.csrf import csrf_exempt
from .dysms_python.demo_sms_send import *
import uuid


def user_register(request):
    context = dict()
    form_obj = UserLoginForm()
    if request.method == "POST":
        form_obj = UserLoginForm(request.POST)
        if form_obj.is_valid():
            print(form_obj)
            phone = form_obj.cleaned_data['phone']
            if re.match(r'^1[356789][0-9]{9}$', phone):
                phone = User.objects.filter(phone=phone)
                if phone:
                    context['error_message'] = '此手机号已被注册，请使用别的手机号！'
                    return render(request, 'news/user_register.html', context)
                User.objects.create(phone=request.POST['phone'], password=request.POST['password'])
                return HttpResponseRedirect(reverse("news:user_login"))
            else:
                context['error_message'] = "手机号码的格式不对，请重新输入！"
                return render(request, 'news/user_register.html', context)
        else:
            print(form_obj.errors)
    context['form'] = form_obj
    return render(request, "news/user_register.html", context)


def user_login(request):
    context = dict()
    form = UserLoginForm()
    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            phone = form.cleaned_data['phone']
            password = form.cleaned_data['password']
            user = User.objects.filter(phone=phone, password=password)
            if user:
                user = user[0]
                user = dict(phone=user.phone,
                            portrait=str(user.portrait),
                            nickname=user.nickname,
                            vip=user.vip,
                            integral=user.integral,
                            number=user.number)
                request.session['user'] = user
                request.session['success'] = True
                return HttpResponseRedirect(reverse("news:user_index"))
            else:
                context['error_message'] = "账号或者密码错误！"
    context['form'] = form
    return render(request, "news/user_login.html", context)


# def main_index(request):
#     context = dict()
#     qcode = models.make_code("http://127.0.0.1:8080/media/xxx/1.jpg")
#
#     img_io = BytesIO()
#     qcode = qrcode.make('http://www.baidu.com', border=1)
#     qcode.save(img_io, format='jpeg')
#     img_io.seek(0)
#     context['qcode'] = "data:image/jpg;base64,%s" % str(base64.b64encode(img_io.read()))[2: -1]
#     return render(request, "news/main_index.html", context)


def get_password_1(request):
    return HttpResponseRedirect(reverse("news:forget_password"))


def reset_password(request, phone):
    if request.method == "POST":
        user = User.objects.get(phone=phone)
        pwd = request.POST['password']
        pwd1 = request.POST['password1']
        if pwd == pwd1:
            user.password = pwd
            user.save()
            msg = '修改密码成功'
            return render(request, 'news/reset_password.html', locals())
        else:
            return render(request, 'news/reset_password', {'msg': '两次密码不一致'})
    return render(request, 'news/reset_password.html', locals())


def forget_password(request):
    context = dict()
    if request.method == "POST":
        phone = request.POST.get('phone', None)
        if phone:
            return HttpResponseRedirect(reverse('news:reset_password', args=(phone,)))
        error_message = '请输入正确手机号'
        context['error_message'] = error_message
        return render(request, 'news/forget_password.html', context)
    return render(request, 'news/forget_password.html', context)


def user_index(request):
    context = dict()
    if request.session['user']:
        print(request.session['user'])
        u = request.session['user']
        user = User.objects.filter(phone=u.get('phone'))
        # print(user[0].portrait.url)
        if user:
            if request.method == 'POST':
                nickname = request.POST.get('nickname', None)
                portrait = request.FILES.get('portrait', None)
                # print(request.FILES['portrait'])
                if nickname:
                    User.objects.filter(phone=u.get('phone')).update(nickname=nickname)
                if portrait:
                    print('111')
                    print(portrait)
                    user = User.objects.get(phone=u.get('phone'))
                    user.portrait = request.FILES['portrait']
                    user.save()


                context['msg'] = '个人页面已设置好'
                context['user'] = User.objects.get(phone=u.get('phone'))
            return render(request, 'news/user_index.html', context)
    return render(request, 'news/user_index.html', context)


def handle_uploaded_file(file_obj):
    now = timezone.now()
    filename = "%s%s%s%s%s%s%s%s%s" % (
        now.year, now.month, now.day, now.hour, now.minute, now.second,
        now.microsecond, random.randint(100000, 999999), '.html')
    file_path = os.path.join(settings.USER_UPLOAD_DIR, filename)
    print(file_path)
    b = bytes(file_obj, encoding='utf-8')
    with open(file_path, 'wb+') as f:
        f.write(b)
    return 'bbc/' + filename


def publish_content(request):
    if request.session['user']:
        u = request.session['user']
        user = User.objects.filter(phone=u.get('phone'))
        if user:
            print(user)
            if user[0].number >= '1':
                # form = ArticleForm()
                # print(form.errors)
                if request.method == "POST":
                    # form = ArticleForm(request.POST, request.FILES)
                    # if form.is_valid():
                        Article.objects.create(title=request.POST['title'],
                                               sort=request.POST['sort'],
                                               author=user[0],
                                               source=request.POST['source'],
                                               abstract=request.POST['abstract'],
                                               images=request.FILES['images'],
                                               content=request.POST['content'])
                        print('11111111111111111111111111')
                        # result = form.save()
                        # print('222222222222222222222222222')
                        # print(result)
                        # if result:
                        return render(request, 'bbc/publish_content_success.html', locals())
                else:
                        # form = ArticleForm()
                    msg = '发布失败，请重新填写'
                    return render(request, 'bbc/publish_content.html', locals())
                # form = ArticleForm()
                # return render(request, 'bbc/publish_content.html', locals())
            else:
                    msg = '剩余次数不足'
                    return render(request, 'news/main_index.html', locals())
        else:
            form = ArticleForm()
            return render(request, 'news/user_login.html', locals())
    else:
        return HttpResponseRedirect(reverse('news:user_login'))


def publish_content_success(request):
    context = dict()
    return render(request, "bbc/publish_content_success.html", context)


def user_login_main(request):
    context = dict()
    return render(request, "news/main_index.html", context)


def mypublish(request):
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.filter(phone=u.get('phone'))

        if user:
            # article = user.article_set.all()
            # print(article)
            article = Article.objects.filter(author=user[0])
            not_article = Article.objects.filter(audit_status='3')
            article_1 = Article.objects.filter(audit_status='0')
            article_yes = Article.objects.filter(audit_status='1')
            # print('这是待审核的：',article_1)
            # print('这是审核通过的：',article_yes)
            # print('这是我发布的：',article)
            # print('这是未通过的：',not_article)
            for i in article_yes:
                print(i.images)
            #  所有新闻
            rag = Paginator(article, 4)

            page = request.GET.get('page')
            try:
                cust_1 = rag.page(page)
            except PageNotAnInteger:
                cust_1 = rag.page(1)
            except EmptyPage:
                cust_1 = rag.page(rag.num_pages)

            for i in cust_1:
                print('这是图片',i.images.url)
            # 通过新闻
            rag = Paginator(article_yes, 4, 2)
            page = request.GET.get('page')
            try:
                cust_2 = rag.page(page)
            except PageNotAnInteger:
                cust_2 = rag.page(1)
            except EmptyPage:
                cust_2 = rag.page(rag.num_pages)

            # 未通过新闻
            rag = Paginator(not_article, 4, 2)
            page = request.GET.get('page')
            try:
                cust_3 = rag.page(page)
            except PageNotAnInteger:
                cust_3 = rag.page(1)
            except EmptyPage:
                cust_3 = rag.page(rag.num_pages)

            # 待审核新闻
            rag = Paginator(article_1, 4, 2)
            page = request.GET.get('page')
            try:
                cust_4 = rag.page(page)
            except PageNotAnInteger:
                cust_4 = rag.page(1)
            except EmptyPage:
                cust_4 = rag.page(rag.num_pages)
            context['not_article'] = cust_3
            context['article_1'] = cust_4
            context['article_yes'] = cust_2
            context['article'] = cust_1
            context['user'] = user
            return render(request, "news/mypublish.html", context)

        return render(request, 'news/user_login', {"msg": "没有该用户请重新登录"})
    return HttpResponseRedirect(reverse('news:user_login'))


def article_detail(request, article_id):
    Article.objects.filter(pk=article_id).update(view_number=F('view_number') + 1)
    article = Article.objects.get(pk=article_id)
    comments = Comment.objects.filter(article=article)
    context = dict()
    context['article'] = article
    context['comments'] = comments
    newss = Article.objects.filter(pub_date__lt=timezone.now()).order_by()[:5]
    context['l_news'] = newss
    user_id = request.session.get('users', None)
    if user_id:
        user = User.objects.get(pk=user_id)
        context['user'] = user
        if Zan.objects.filter(news=article, user=user).exists():
            context['likes'] = '已点赞'
    return render(request, 'news/article_detail.html', context)


def alert_pwd_1(request):
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.filter(phone=u.get('phone'))
        if user:
            context['users'] = user
            if request.method == 'POST':
                return render(request, 'news/alert_pwd_2.html', context)
            return render(request, 'news/alert_pwd_1.html', context)
    return render(request, 'news/user_login.html')


def alert_pwd_2(request):
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.filter(phone=u.get('phone'))
        if user:
            context['users'] = user
            pwd = request.POST.get('password', 'None')
            if pwd:
                user.update(password=pwd)
                msg = '修改密码成功'
                return render(request, 'news/alert_pwd_2.html', locals())

            return render(request, 'news/alert_pwd_2', {'msg': '两次密码不一致'})
    return HttpResponseRedirect(reverse('news:user_login'))


def recharge(request):    #t充值会员
    context = dict()
    number = str(math.ceil(time.time()))
    if request.session['user']:
        u = request.session['user']
        user = User.objects.get(phone=u.get('phone'))
        print(User.objects.all())
        if user:

            context['user'] = user
            if request.method == 'POST':
                vip = request.POST.get('g', None)
                zf = request.POST.get('z', None)
                if zf:
                    if vip:
                        if int(user.vip) < int(vip):
                            numbers = request.POST['number']
                            rmb = request.POST['rmb']
                            user.vip = vip
                            user.number = F('number') + numbers
                            Charge.objects.create(pays_number=number, pays_money=int(rmb), users=user)
                            user.save()
                            context['succeed'] = '充值成功'
                        else:
                            context['succeed'] = '你已经是vip' + user.vip
                    else:
                        context['succeed'] = '请选择购买方式'
                else:
                    context['succeed'] = '请选择支付方式'

            context['user'] = user
            return render(request, 'news/recharge.html', context)
    return render(request, 'news/user_login.html', context)


def exchange(request):  #t兑换会员
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.get(phone=u.get('phone'))
        print(User.objects.all())
        if user:

            context['user'] = user
            if request.method == 'POST':
                vip = request.POST['g']
                user.vip = vip
                if vip == '1':
                    user.integral = F('integral') - 20
                    user.number = F('number') + 2
                    Bill.objects.create(pays='兑换会员', money=-20,user=user)
                elif vip == '2':
                    user.integral = F('integral') - 50
                    user.number = F('number') + 5
                    Bill.objects.create(pays='兑换会员', money=-50, user=user)
                elif vip == '3':
                    user.integral = F('integral') - 100
                    user.number = F('number') + 10
                    Bill.objects.create(pays='兑换会员', money=-100, user=user)
                user.save()
                context['succeed'] = '兑换成功'
                return render(request, 'news/exchange.html', context)
            return render(request, 'news/exchange.html', context)
    return render(request, 'news/user_login.html')


def my_vip(request): #我的会员
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.get(phone=u.get('phone'))

        if user:
            user_vip = Charge.objects.filter(users=user)
            rag = Paginator(user_vip, 5)
            page = request.GET.get('page')
            try:
                cust = rag.page(page)
            except PageNotAnInteger:
                cust = rag.page(1)
            except EmptyPage:
                cust = rag.page(rag.num_pages)
            context['user_vip'] = cust
            context['user'] = user
            return render(request, 'news/my_vip.html', context)
    else:
        return render(request, 'news/user_login.html')


def my_integral(request):  #我的积分
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.get(phone=u.get('phone'))
        print(User.objects.all())
        if user:
            intagral = Bill.objects.filter(user=user)
            rag = Paginator(intagral, 5)
            page = request.GET.get('page')
            try:
                cust = rag.page(page)
            except PageNotAnInteger:
                cust = rag.page(1)
            except EmptyPage:
                cust = rag.page(rag.num_pages)
            context['user'] = user
            context['intagral'] = cust
            return render(request, 'news/my_integral.html', context)
    return render(request, 'news/user_login.html')


def my_message(request): #消息
    context = dict()
    if request.session['user']:
        u = request.session['user']
        user = User.objects.get(phone=u.get('phone'))

        if user:
            context['users'] = user

            return render(request, 'news/my_message.html', context)
    return render(request, 'news/user_login.html')


def user_logout(request):
    del request.session['user']
    return HttpResponseRedirect(reverse('news:user_login'))


# def user_data(request):
#     context = dict()
#     return render(request, "news/user_data.html", context)


@csrf_exempt
def code(request):
        __business_id = uuid.uuid1()

        # print(__business_id)
        params = dict(code=random.randint(10000, 999999))
        request.session['code'] = params['code'], request.session.set_expiry(120)
        # params = "{\"code\":\"12345\",\"product\":\"云通信\"}"

        # params = u'{"name":"wqb","code":"12345678","address":"bz","phone":"13000000000"}'

        send = send_sms(__business_id, request.POST['phone'], "既念即觉一生一重", "SMS_151578730", params)
        print(send.decode('utf8'))
        return HttpResponse()


def mores(request):
    context = dict()
    user = request.session.get('user', None)
    news_flash = Article.objects.filter(sort='快讯')
    news1 = Article.objects.all().order_by()[:5]
    context['news1'] = news1
    context['news'] = news1[0]
    context['news_flash'] = news_flash
    if user:
        user = User.objects.get(pk=user)
        context['user'] = user
    return render(request, 'bbc/article_mores.html', context)


def main_index(request):
    if request.session['user']:
        u = request.session['user']
        user = User.objects.filter(phone=u.get('phone'))
        context = dict()
        # user = request.session.get('user', None)
        news_flash = Article.objects.filter(pub_date__lt=timezone.now()).order_by()[:5]
        news_technology = Article.objects.filter(sort='技术')
        news_news = Article.objects.filter(sort='新闻')
        news_policy = Article.objects.filter(sort='政策')
        news_market = Article.objects.filter(sort='行情')
        context['news_flash'] = news_flash
        context['news_news'] = news_news
        context['news_policy'] = news_policy
        context['news_market'] = news_market
        context['news_technology'] = news_technology
        context['newsr'] = news_flash[0]
        if user:
            context['users'] = user
            print(news_flash[0])
    # qcode = models.make_code("http://127.0.0.1:8080/media/xxx/1.jpg")
    #
    # img_io = BytesIO()
    # qcode = qrcode.make('http://www.baidu.com', border=1)
    # qcode.save(img_io, format='jpeg')
    # img_io.seek(0)
    # context['qcode'] = "data:image/jpg;base64,%s" % str(base64.b64encode(img_io.read()))[2: -1]
        return render(request, "news/main_index.html", context)
    return HttpResponseRedirect(reverse("news:user_login"))


def zan(request, article_id):  #点赞
    content = dict()
    user = request.session.get('user', None)
    if user:
        Article.objects.filter(pk=article_id).update(like_number=F('like_number') + 1)
        Zan.objects.create(article=Article.objects.get(pk=article_id),
                           user=User.objects.get(phone=user['phone']))
    return HttpResponseRedirect(reverse('news:article_detail', args=(article_id,)))


def share(request, article_id): # 分享
    # content = dict()
    user = request.session.get('user', None)
    if user:
        # print(User.objects.get(phone=user['phone']))
        Article.objects.filter(pk=article_id).update(share_number=F('share_number') + 1)
        User.objects.filter(phone=user['phone']).update(integral=F('integral') + 50)
        Bill.objects.create(user=User.objects.get(phone=user['phone']), pays='分享文章', money=50)
    return HttpResponseRedirect(reverse('news:article_detail', args=(article_id,)))


def comment(request, article_id): #评论
    # content = dict()
    user = request.session.get('user', None)
    print('0000000000000000000000')
    print(user)
    print(request.POST)
    if user:
        print('111111111111111')
        news = Article.objects.get(pk=article_id)
        print(request.POST['content'])
        Comment.objects.create(author=User.objects.get(phone=user['phone']),
                               content=request.POST['content'],
                               article=news,
                               nickname=news.author.id)
    return HttpResponseRedirect(reverse('news:article_detail', args=(article_id,)))



